package com.itluma.isWOak.authc;

import com.itluma.isWOak.realm.MyRealm;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author 飞鸟
 * @create 2021-04-01 10:25
 */


public class UserAuthenticationFilter extends FormAuthenticationFilter{

    private Logger log = LoggerFactory.getLogger (UserAuthenticationFilter.class);

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue){
        if (isLoginRequest (request, response) && isLoginSubmission (request, response)) {
            //需要重新登录
            return false;
        }

        return super.isAccessAllowed (request, response, mappedValue);
    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception{
        WebUtils.issueRedirect (request, response, getSuccessUrl ());
        return false;
    }

    //处理验证码问题
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception{

        HttpServletRequest req = (HttpServletRequest) request;

        HttpSession session = req.getSession ();

        String captcha = (String) session.getAttribute ("captcha");

        log.info ("表单验证码为: " + captcha);

        String code = req.getParameter ("code");

        if (code != null && !code.equalsIgnoreCase (captcha)) {
            req.setAttribute ("codeerror", "验证码输入错误");
            log.info ("设置了验证码输入错误");
            return true;
        }

        return super.onAccessDenied (request, response);
    }
}
